#import "WebCacheOperation.h"

/**
 * A WebCacheOperation is an object representing a single operation
 * of downloading and parsing elements from a website.
 *
 * @author      James Lin
 * @version     1.3.1
 * @since       1.0.2
 * @see         WebParsable
 */
@implementation WebCacheOperation

/**
 * Initialize the website caching operation.
 *
 * @param webParsable      the parsable website source
 * @return                 the initialized WebCacheOperation
 * @see	                   WebParsable
 */
- (id)initWithWebParsable:(id<WebParsable>)webParsable {
	if (self = [super init]) {
		webSource = webParsable;
		_isExecuting = NO;
		_isFinished = NO;
	}
	return self;
}

/**
 * Notify that the operation is concurrent.
 */
- (BOOL)isConcurrent {
	return YES;
}

/**
 * Start the website caching operation.
 */
- (void)main {
	//NSLog(@"Starting to run web caching operation...");
	
	if (self.isCancelled) {
		return;
	}
	
	// Begin downloading source code
	if ([webSource downloadSourceCode]) {
		if (self.isCancelled) {
			return;
		}
		[[webSource delegate] connectionDidFinish:@"Connection successful." 
										  results:[webSource parseElements]];
	} else {
		if (self.isCancelled) {
			return;
		}
		[[webSource delegate] connectionDidFail:@"Connection failed."];
	}
}

/**
 * Deallocate the website caching operation.
 */
- (void)dealloc {
	[webSource dealloc];
	webSource = nil;
	[super dealloc];
}

@end
